﻿/*Universidad del Valle de Guatemala
Megaproyecto
CanSat Fase 2, Módulo: Software de Control en Tierra
Ana Silvia Gonzáles Torres
10194*/

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Linq;
using System.Windows.Forms;
using System.IO.Ports;
using System.IO;

namespace Interfaz_V1
{
    public partial class Form1 : Form
    {

        //VARIABLES GLOBALES
        delegate void graphAltCCallback(double val1, int val2);
        delegate void graphVoltCallback(float val);
        delegate void graphPreassureCallback(long val1, double val2, int val3);
        delegate void graphTempCallback(double val1, int val2);
        delegate void addPayloadCallback(String val);
        delegate void addContainerCallback(String val);
        delegate void addCsvCallback(int val1, String val2);
        delegate void dispCountPCallback(int val);
        delegate void dispCountCCallback(int val);
        delegate void dispTimePCallback(int val);
        delegate void dispTimeCCallback(int val);
        delegate void graphAccelXCallback(double val, int val2);
        delegate void graphAccelYCallback(double val, int val2);
        delegate void graphAccelZCallback(double val, int val2);
        delegate void graphAccelCallback(List<double> val, int val2);
        delegate void graphAngleCallback(double val1, double val2, double val3);
        delegate void displayTestCallback(Label val1, double val2, String val3);
        delegate void displayTestPCallback(String val);
        delegate void ShowConfirmationCallback(String val);
        delegate void ShowStatusCallback(String val, Label label);
        delegate void testResultCallback(PictureBox val1, int val2);
        delegate void graphAngleXCallback(double val1);
        delegate void graphAngleYCallback(double val1);
        delegate void graphAngleZCallback(double val1);
        

        private static object synTemp;

        int mode;
        String portName;
        String pendingF,pendingP, pendingC;
        String lastTeamID;
        char lastXBEEID;
        int lastPacket, missionTime;
        int lastPacketPayload, missionTimePayload;
        int lastPacketContainer, missionTimeContainer;
        int currentTemp;
        int expectingP, expectingC;
        Image[] statusImg;
        int countP;
        String waiting, fileP, fileC;
        List<String> resultsP, resultsC, namesTP, namesTC;
        String testAcel;
        int sensorSet;
                

        //CONSTANTES
        const int PLENGHT = 51;
        const int CLENGTH = 26;
        const char ENDCHAR = (char)13;
        const char ENDBULK = (char)14;
        int[] AC1 = new int[] { 8574, 8679, 6871, 6871 };
        int[] AC2 = new int[] { -1189, -1219, -986, -986 };
        int[] AC3 = new int[] { -14504, -14374, -14554, -14554 };
        int[] AC4 = new int[] { 34476, 34151, 34552, 34552 };
        int[] AC5 = new int[] { 24638, 24686, 24905, 24905 };
        int[] AC6 = new int[] { 21376, 22910, 18070, 18070 };
        int[] B1 = new int[] { 5498, 6515, 5498, 5498 };
        int[] B2 = new int[] { 64, 50, 50, 50 };
        int[] MB = new int[] { -32768, -32768, -32768, -32768 };
        int[] MC = new int[] { -11075, -11786, -11075, -11075 };
        int[] MD = new int[] { 2432, 3011, 2432, 2432 };
        const int OSS = 0;
        long[] PO = new long[] { 101325, 101325, 101325, 101325 };

        const int EXITCODE = 99;
        const int INITCODE = 98;
        const String TEAMID = "2653";
        const double MINDX = 50;
        const double MINDY = -540;
        const double MINDZ = 75;
        const double MAXDX = 540;
        const double MAXDY = -50;
        const double MAXDZ = 875;


        //FUNCIONES DEL PROGRAMA

        #region
        /**Convierte los bytes en hexadecimal a decimal**/
        public String hexToStr(byte[] hex)
        {
            int val;
            String cadena = "";

            for (int i = 0; i < hex.Length; i++)
            {
                val = Convert.ToInt32(hex[i].ToString().ToUpper());
                cadena += (char)(val);

            }

            return cadena;
        }

        /**Espera a que le hayan confirmado la conexión para load desde memoria**/
        private void confirmMemory(byte[] package, int source)
        {

            String cadena;
            int pos;

            lock (pendingF)
            {
                pendingF += hexToStr(package);
                pos = pendingF.IndexOf(ENDCHAR);

                while (pos >= 0)
                {

                    cadena = pendingF.Substring(0, pos);
                    if (pendingF.Length > 1)
                        pendingF = pendingF.Substring(pos + 1);
                    else
                        pendingF = "";

                    if (expectingC != -1)
                    {
                        MessageBox.Show("Confirmation from Container received " + cadena);
                        expectingC = -1;

                    }

                    if (mode == 3)
                    {
                        if (expectingP == 0)
                        {
                            MessageBox.Show("Confirmation from memory received " + cadena);
                            expectingP = -1;
                            requestP(12);
                        }
                        else
                        {
                            cadena = "x" + TEAMID + "," + cadena;
                        }
                    }

                    if ((cadena.Length == PLENGHT))
                    {
                        processPayload(cadena);
                        addPayload(cadena);

                    }
                    else if ((cadena.Length == CLENGTH))
                    {
                        processContainer(cadena);
                        addContainer(cadena);
                    }

                    pos = pendingF.IndexOf(ENDCHAR);
                }

            }
        }

        /**Función que crea un nuevo thread para agregar paquete al listado**/
        private void addPackage(byte[] package)
        {
            String cadena;
            int pos; 

            lock (pendingF)
            {
                pendingF += hexToStr(package);
                pos = pendingF.IndexOf(ENDCHAR);

                while (pos >= 0)
                {

                    cadena = pendingF.Substring(0, pos);
                    if (pendingF.Length > 1)
                        pendingF = pendingF.Substring(pos + 1);
                    else
                        pendingF = "";

                    if (expectingC != -1)
                    {
                        MessageBox.Show("Confirmation from Container received " + cadena);
                        expectingC = -1;
                        
                    }

                    if (mode == 3)
                    {
                        if (expectingP == 0)
                        {
                            MessageBox.Show("Confirmation from Paiload received " + cadena);
                            expectingP = -1;
                            requestP(12);
                        }
                        else
                        {
                            cadena = "x" + TEAMID + "," + cadena;
                        }
                    }

                    if ((cadena.Length == PLENGHT))
                    {
                        processPayload(cadena);
                        addPayload(cadena);

                    }
                    else if ((cadena.Length == CLENGTH))
                    {
                        processContainer(cadena);
                        addContainer(cadena);
                    }

                    pos = pendingF.IndexOf(ENDCHAR);
                }

            }

        }

        /**Función que añade un paquete del Payload a la lista**/
        public void addPayload(String packet)
        {

            if (listReceivedPacketsPayload.InvokeRequired)
            {
                addPayloadCallback call = new addPayloadCallback(addPayload);
                this.Invoke(call, new object[] { packet });
            }
            else
                this.listReceivedPacketsPayload.Items.Add(packet);

        }

        /**Función que añade un paquete del Container a la lista**/
        public void addContainer(String packet)
        {

            if (listReceivedPacketsContainer.InvokeRequired)
            {
                addContainerCallback call = new addContainerCallback(addContainer);
                this.Invoke(call, new object[] { packet });
            }
            else
                this.listReceivedPacketsContainer.Items.Add(packet);

        }

        /**Función que procesa un nuevo paquete cuya fuente es el container**/
        public void processContainer(String package)
        {
            List<String> data = package.Split(',').ToList<String>();
            float val = 0;
            String finalcsv = "";

            for (int i = 0; i < data.Count; i++)
            {
                switch (i)
                {
                    case 0:
                        if (data[i].Length > 0)
                        {
                            lastXBEEID = data[i][0];
                        }
                        if (data[i].Length > 1)
                            lastTeamID = data[i].Substring(1);
                        finalcsv = lastTeamID + ",";
                        break;
                    case 1:
                        if (float.TryParse(data[i], out val))
                        {
                            if (lastPacket < (int)val)
                                lastPacket = (int)val;
                            if (lastPacketContainer < (int)val)
                                lastPacketContainer = (int)val;
                            displayCountC(lastPacket);
                            finalcsv += lastPacket + ",";
                        }
                        
                        break;
                    case 2:
                        if(float.TryParse(data[i],out val))
                        {
                            if (missionTime < (int)val)
                                missionTime = (int)val;
                            if (missionTimeContainer < (int)val)
                                missionTimeContainer = (int)val;
                            displayTimeC(missionTimeContainer);
                            finalcsv += missionTime + ",";
                        }
                        break;
                    case 3:
                        if(float.TryParse(data[i],out val))
                        {
                            double preasure = calcPressureC((int)val);
                            double altitude = calcAltitude(preasure);
                            graphAltitud(altitude, missionTimeContainer);
                            finalcsv += altitude.ToString("0.00");
                        }
                        break;
                    case 4:
                        String status = "";
                        if (data[i].Length > 0)
                        {
                            switch (data[i][0])
                            {
                                case 'G':
                                    status = "Ground, ";
                                    break;
                                case 'V':
                                    status = "Flight, ";
                                    break;
                                case '1':
                                    status = "Point 1, ";
                                    break;
                                case 'L':
                                    status = "Point 2 Open, ";
                                    break;
                                default:
                                    status = ", ";
                                    break;
                            }
                        }
                        if (data[i].Length > 1)
                        {
                            switch (data[i][1])
                            {
                                case 'N':
                                    status += "Close";
                                    break;
                                case 'Y':
                                    status += "Open";
                                    break;
                            }
                        }

                        showStatus("Container Status: " + status, labelStatusC);
                        break;
                }

            }

            addCsv(2, finalcsv);

            
        }

        public void showStatus(String status, Label dest)
        {
            if (dest.InvokeRequired)
            {
                ShowStatusCallback call = new ShowStatusCallback(showStatus);
                this.Invoke(call, new object[] { status, dest });
            }
            else
                dest.Text = status;
                
        }

        /**Función que procesa un nuevo paquete cuya fuente es el payload**/
        public void processPayload(string package)
        {

            List<String> data = package.Split(',').ToList<String>();
            float val = 0;
            String finalcsv = "";
            String extras = "";

            for (int i = 0; i < data.Count; i++)
            {
                switch ((i))
                {
                    
                    case 0:
                        if (data[i].Length > 0)
                        {
                            lastXBEEID = data[i][0];
                        }
                        if (data[i].Length > 1)
                            lastTeamID = data[i].Substring(1);
                        finalcsv = lastTeamID + ",";
                        break;
                    case 1:
                        if(float.TryParse(data[i],out val))
                        {

                            if(lastPacket < ((int)val))
                                lastPacket = (int)val;
                            if (lastPacketPayload < ((int)val))
                                lastPacketPayload = (int)val;
                            displayCountP(lastPacketPayload);
                            finalcsv += lastPacketPayload + ",";
                        }
                        break;
                    case 2:
                        if(float.TryParse(data[i],out val))
                        {
                            if(missionTime < ((int)val))
                                missionTime = (int)val;
                            if (missionTimePayload < ((int)val))
                                missionTimePayload = (int)val;
                            displayTimeP(missionTimePayload);
                            finalcsv += missionTimePayload + ",";
                        }
                        break;
                    case 3:
                        if (float.TryParse(data[i], out val))
                        {
                            long preasure = calcPreasure((int)val);
                            double altitude = calcAltitude(preasure);
                            graphPreassure(preasure, altitude, missionTimePayload);
                            finalcsv += altitude.ToString("0.00") + ",";
                            extras = "," + preasure.ToString("0.00");
                        }
                        break;
                    case 4:
                        if (float.TryParse(data[i], out val))
                        {
                            double temp = (calcTemp((int)val));
                            graphTemp(temp, missionTimePayload);
                            finalcsv += temp.ToString("0.00") + ",";
                        }
                        break;
                    case 5:
                        if (float.TryParse(data[i], out val))
                        {
                            float volt = calcVoltage((int)val);
                            graphVoltage(volt);
                            finalcsv += volt.ToString("0.00") + ",";
                        }
                        break;
                    case 6:
                        List<long> acel = getAceleration(data[i]);
                        
                        List<double> angl = calcAngle(acel[0], acel[1], acel[2]);
                        List<double> acelF = calcAcele(acel);
                        graphAcceleration(acelF, missionTimePayload);
                        graphAngle(angl[0], angl[1], angl[2]);
                        graphAngleX(angl[0]);
                        graphAngleY(angl[1]);
                        graphAngleZ(angl[2]);
                        finalcsv += angl[0].ToString("0.00") + "," + angl[1].ToString("0.00") + "," + angl[2].ToString("0.00") + ",";
                        finalcsv += acelF[0].ToString("0.00") + "," + acelF[1].ToString("0.00") + "," + acelF[2].ToString("0.00");
                        break;
                    case 7:
                        String status = "";
                        if (data[i].Length > 0)
                        {
                            switch (data[i][0])
                            {
                                case 'G':
                                    status = "Ground, ";
                                    break;
                                case 'V':
                                    status = "Flight, ";
                                    break;
                                case '1':
                                    status = "Point 1, ";
                                    break;
                                case 'L':
                                    status = "Point 2 Open, ";
                                    break;
                                default:
                                    status = ", ";
                                    break;
                            }
                        }
                        if (data[i].Length > 1)
                        {
                            switch (data[i][1])
                            {
                                case 'N':
                                    status += "Close";
                                    break;
                                case 'Y':
                                    status += "Open";
                                    break;
                            }
                        }

                        //showStatus("Payload Status: " + status, labelStatusP);

                        break;


                }

            }

            addCsv(1, finalcsv + extras);

        }

        public List<double> calcAcele(List<long> data)
        {
            List<double> resp = new List<double>();

            for (int i = 0; i < data.Count; i++)
            {
                resp.Add(data[i] / 100.00);
            }

            return resp;
        }

        /**Función que separa los valores obtenidos de la aceleración por ejes**/
        public List<long> getAceleration(String data)
        {
            List<long> resp = new List<long>();
            long aceleration;
            String tmp = "";

            for (int j = 0; j < data.Length; j++)
            {

                if ((j > 0) && ((data[j] == '+') || (data[j] == '-')))
                {
                    if (!(long.TryParse(tmp, out aceleration)))
                        aceleration = 0;
                    tmp = "";
                    resp.Add(aceleration);
                }
                tmp += data[j];

            }

            if (tmp.Length > 0)
            {
                if (!(long.TryParse(tmp, out aceleration)))
                    aceleration = 0;
                tmp = "";
                resp.Add(aceleration);
            }

            while (resp.Count < 3)
                resp.Add(0);
            return resp;
        }

        /**Función que limpia para iniciar nueva transmición**/
        public void initTrans()
        {

            missionTime = -1;
            missionTimeContainer = -1;
            missionTimePayload = -1;
            lastPacket = -1;
            lastPacketContainer = -1;
            lastPacketPayload = -1;
            lastTeamID = "";
            lastXBEEID = ' ';
            listReceivedPacketsPayload.Items.Clear();
            listReceivedPacketsContainer.Items.Clear();
            listCsvPacketsP.Items.Clear();
            listCsvPacketsC.Items.Clear();
            chartAltitudeP.Series[0].Points.Clear();
            chartVoltage.Series[0].Points.Clear();
            chartPreassureTemp.Series[0].Points.Clear();
            chartTemp.Series[0].Points.Clear();
            chartAccel.Series[0].Points.Clear();
            chartAccel.Series[1].Points.Clear();
            chartAccel.Series[2].Points.Clear();
            chartAltitudeC.Series[0].Points.Clear();
            pendingF = "";
            pendingP = "";
            pendingC = "";
            currentTemp = 0;
            synTemp = new object();
            waiting = "0005";
            //sensorSet = 0;

            
        }

        /**Función que grafica la aceleración del Payload en el eje X**/
        public void graphXAxis(double val, int time)
        {
            if (chartAccel.InvokeRequired)
            {
                graphAccelXCallback call = new graphAccelXCallback(graphXAxis);
                this.Invoke(call, new object[] { val, time });
            }
            else
            {
                this.chartAccel.Series[0].Points.AddXY(time, val);
            }
        }

        /**Función que grafica la aceleración del Payload en el eje Y**/
        public void graphYAxis(double val, int time)
        {
            if (chartAccel.InvokeRequired)
            {
                graphAccelYCallback call = new graphAccelYCallback(graphYAxis);
                this.Invoke(call, new object[] { val, time });
            }
            else
            {
                this.chartAccel.Series[1].Points.AddXY(time, val);
            }
        }

        /**Función que grafica la aceleración del Payload en el eje Z**/
        public void graphZAxis(double val,int time)
        {
            if (chartAccel.InvokeRequired)
            {
                graphAccelZCallback call = new graphAccelZCallback(graphZAxis);
                this.Invoke(call, new object[] { val, time });
            }
            else
            {
                this.chartAccel.Series[2].Points.AddXY(time, val);
            }
        }

        /**Función que grafica la aceleración del Payload**/
        public void graphAcceleration(List<double> accels, int time)
        {

            if (labelAcel.InvokeRequired)
            {
                graphAccelCallback call = new graphAccelCallback(graphAcceleration);
                this.Invoke(call, new object[] { accels, time });
            }
            else
            {
                for (int i = 0; i < accels.Count; i++)
                {
                    if (i == 0)
                    {
                        graphXAxis(accels[i], time);

                    }
                    else if (i == 1)
                    {
                        graphYAxis(accels[i], time);


                    }
                    else if (i == 2)
                    {
                        graphZAxis(accels[i], time);

                    }
                }
                labelAcel.Text = "Acel: " + accels[0].ToString("0.00") + ", " + accels[1].ToString("0.00") + ", " + accels[2].ToString("0.00") + " (G)";
            }

        }

        /**Función que calcula los angulos**/
        public List<double> calcAngle(double x, double y, double z)
        {

            double anX, anY, anZ;
            List<double> resp = new List<double>();

            anZ = Math.Sqrt(Math.Pow(x, 2) + Math.Pow(y, 2));
            anZ = anZ / z;
            anZ = Math.Atan(anZ);
            anZ = (anZ * 180) / Math.PI;

            anY = Math.Sqrt(Math.Pow(x, 2) + Math.Pow(z, 2));
            anY = y / anY;
            anY = Math.Atan(anY);
            anY = (anY * 180) / Math.PI;
            

            anX = Math.Sqrt(Math.Pow(y, 2) + Math.Pow(z, 2));
            anX = x / anX;
            anX = Math.Atan(anX);
            anX = (anX * 180) / Math.PI;
            resp.Add(anX);
            resp.Add(anY);
            resp.Add(anZ);

            return resp;

        }

        /**Función que grafica la aceleración del Payload**/
        public void graphAngle(double x, double Y, double z)
        {
            if (labelAngle.InvokeRequired)
            {
                graphAngleCallback call = new graphAngleCallback(graphAngle);
                this.Invoke(call, new object[] { x, Y, z });
            }
            else
            {
                /*chartAngle.Series[0].Points.Clear();
                chartAngle.Series[0].Points.AddXY(0, 0);
                chartAngle.Series[0].Points.AddXY(x, 1);/*/
                labelAngle.Text = "Payload Angle: " + x.ToString("0.00") + "°, " + Y.ToString("0.00") + "°, " + z.ToString("0.00") + "°";
            }
        }



        public void graphAngleX(double x)
        {
            if (labelAngle.InvokeRequired)
            {
                graphAngleXCallback call = new graphAngleXCallback(graphAngleX);
                this.Invoke(call, new object[] { x });
            }
            else
            {
                chartAngleX.Series[0].Points.Clear();
                chartAngleX.Series[0].Points.AddXY(0, 0);
                chartAngleX.Series[0].Points.AddXY(x, 1);
            }
        }

        public void graphAngleY(double y)
        {
            if (labelAngle.InvokeRequired)
            {
                graphAngleYCallback call = new graphAngleYCallback(graphAngleY);
                this.Invoke(call, new object[] { y });
            }
            else
            {
                chartAngleY.Series[0].Points.Clear();
                chartAngleY.Series[0].Points.AddXY(0, 0);
                chartAngleY.Series[0].Points.AddXY(y, 1);
            }
        }

        public void graphAngleZ(double z)
        {
            if (labelAngle.InvokeRequired)
            {
                graphAngleZCallback call = new graphAngleZCallback(graphAngleZ);
                this.Invoke(call, new object[] { z });
            }
            else
            {
                chartAngleZ.Series[0].Points.Clear();
                chartAngleZ.Series[0].Points.AddXY(0, 0);
                chartAngleZ.Series[0].Points.AddXY(z, 1);
            }
        }

        /**Función que gráfica el voltaje actual del Payload**/
        public void graphVoltage(float value)
        {


            if (chartVoltage.InvokeRequired)
            {
                graphVoltCallback call = new graphVoltCallback(graphVoltage);
                this.Invoke(call, new object[] { value });
            }
            else
            {
                //value = calcVoltage(value);
                if (value < 1638)
                    this.chartVoltage.Series["Voltage"].Color = Color.Red;
                else if (value < 2458)
                    this.chartVoltage.Series["Voltage"].Color = Color.FromArgb(255, 128, 0);
                else
                    this.chartVoltage.Series["Voltage"].Color = Color.Green;

                this.chartVoltage.Series["Voltage"].Points.Clear();
                this.chartVoltage.Series["Voltage"].Points.AddXY(1, value);
                this.labelVoltagePayload.Text = "Voltage: " + value.ToString("#,##0.00") + " v";
            }
        }


        /**Función que calcula el voltaje del Payload**/
        public float calcVoltage(float val)
        {
            float resp = (float)(val * 2.5 * 2 / 4096);
            return resp;
        }

        /**Función que calcula la presión del Payload**/
        public double calcPressureC(int val)
        {
            //double resp = 100 * (val / 4096.00);
            double resp = val;
            return resp;
        }

        /**Función que grafica la altitud para el payload y para el container**/
        public void graphAltitud(double altitude, int time)
        {
            

            if (chartAltitudeC.InvokeRequired)
            {
                graphAltCCallback call = new graphAltCCallback(graphAltitud);
                this.Invoke(call, new object[] {altitude, time });
            }
            else
            {

                this.chartAltitudeC.Series[0].Points.AddXY(time, altitude);
                this.labelAltitudC.Text = "Altitude: " + altitude.ToString("0.00") + "m";

            }

        }

        /**Función que calcula el voltage del Payload**/
        public float calcVoltage(int val)
        {
            float resp = val * 2.5F * 2 / 4096.00F;
            return resp;
        }

        /**Función que calcula al presión, copiado del datasheet**/
        public long calcPreasure(long val)
        {

            long total, tmpB5, b6, b3, b4, x1, x2, x3, b7;

            tmpB5 = currentTemp;

            b6 = tmpB5 - 4000;
            x1 = (B2[sensorSet] * (b6 * b6) >> 12) >> 11;
            x2 = (AC2[sensorSet] * b6) >> 11;
            x3 = x1 + x2;
            b3 = ((((AC1[sensorSet]) * 4 + x3) << OSS) + 2) >> 2;

            x1 = (AC3[sensorSet] * b6) >> 13;
            x2 = (B1[sensorSet] * ((b6 * b6) >> 12)) >> 16;
            x3 = ((x1 + x2) + 2) >> 2;
            b4 = (AC4[sensorSet] * (x3 + 32768)) >> 15;
    
            b7 = ((val - b3) * (50000 >> OSS));
            if (b7 < 0x80000000)
                total = (b7 << 1)/b4;
            else
                total = (b7/b4) << 1;
    
            x1 = (total >> 8) * (total >> 8);
            x1 = (x1 * 3038) >> 16;
            x2 = (-7357 * total) >> 16;
            total += (x1 + x2 + 3791) >> 4;


            return total;

        }

        public double calcAltitude(double val)
        {
            double total, extra, extra2;

            extra = 1/5.255;
            extra2 = val / PO[sensorSet];

            extra = Math.Pow(extra2, extra);

            total = 44330 * (1 - extra);

            return total;

        }

        /**Función que grafica la presión del Payload**/
        public void graphPreassure(long pres, double alt, int time)
        {

            if (chartPreassureTemp.InvokeRequired)
            {
                graphPreassureCallback call = new graphPreassureCallback(graphPreassure);
                this.Invoke(call, new object[] { pres, alt, time });
            }
            else
            {
                this.chartPreassureTemp.Series[0].Points.AddXY(time, pres);
                this.labelPareassure.Text = "Air Preassure: " + pres.ToString("#,##0.00") + " Pa";
                this.chartAltitudeP.Series[0].Points.AddXY(time, alt);
                this.labelAltitudePayload.Text = "Altitude: " + alt.ToString("#,###0.00") + " m";

            }

        }

        /**Función que calcula la temperatura**/
        public double calcTemp(int val)
        {
            int total, x1, x2;


            x1 = ((val - AC6[sensorSet]) * AC5[sensorSet]) >> 15;
            x2 = (MC[sensorSet] << 11) / (x1 + MD[sensorSet]);
            total = x1 + x2;
            lock (synTemp)
            {
                currentTemp = (int)total;
            }

            total = ((total + 8) >> 4) / 10;

            return total;
        }

        /**Función que grafica la presión del Payload**/
        public void graphTemp(double temp, int time)
        {

            

            if (chartTemp.InvokeRequired)
            {
                graphTempCallback call = new graphTempCallback(graphTemp);
                this.Invoke(call, new object[] { temp, time });
            }
            else
            {
                this.chartTemp.Series[0].Points.AddXY(time, temp);
                this.labelTemperature.Text = "Air Temperature: " + temp.ToString("0.00") + " °C";
            }

        }

        /**Función que muestra cuantos paquetes del payload han sido transmitidos**/
        public void displayCountP(int count)
        {
            if (labelCountP.InvokeRequired)
            {
                dispCountPCallback call = new dispCountPCallback(displayCountP);
                this.Invoke(call, new object[] { count });
            }
            else
            {
                this.labelCountP.Text = "Packets Transmitted: " + count;
            }
        }

        /**Función que muestra cuantos paquetes del container han sido transmitidos**/
        public void displayCountC(int count)
        {
            if (labelCountC.InvokeRequired)
            {
                dispCountCCallback call = new dispCountCCallback(displayCountC);
                this.Invoke(call, new object[] { count });
            }
            else
            {
                this.labelCountC.Text = "Packets Transmitted: " + count;
            }
        }

        /**Función que muestra el tiempo de misión según payload**/
        public void displayTimeP(int count)
        {
            if (labelTimeP.InvokeRequired)
            {
                dispTimePCallback call = new dispTimePCallback(displayTimeP);
                this.Invoke(call, new object[] { count });
            }
            else
            {
                this.labelTimeP.Text = "Mission Time: " + count+ " s";
            }
        }

        /**Función que muestra el tiempo de misión según container*/
        public void displayTimeC(int count)
        {
            if (labelCountC.InvokeRequired)
            {
                dispTimeCCallback call = new dispTimeCCallback(displayTimeC);
                this.Invoke(call, new object[] { count });
            }
            else
            {
                this.labelTimeC.Text = "Mission Time: " + count + "s";
            }
        }

        /**Grafica los datos guardados en un archivo de payload**/
        public void readPayload(string package)
        {

            List<String> data = package.Split(',').ToList<String>();
            float val = 0;
            List<double> acel = new List<double>();
            List<double> angl = new List<double>();

            double currentAlt = 0;

            for (int i = 0; i < data.Count; i++)
            {
                switch ((i))
                {

                    case 0:
                            lastTeamID = data[i];
                        break;
                    case 1:
                        if (float.TryParse(data[i], out val))
                        {
                            lastPacketPayload = (int)val;
                            displayCountP(lastPacketPayload);
                        }
                        break;
                    case 2:
                        if (float.TryParse(data[i], out val))
                        {
                            missionTimePayload = (int)val;
                            displayTimeP(missionTimePayload);
                        }
                        break;
                    case 3:
                        if (float.TryParse(data[i], out val))
                        {
                            currentAlt = val;
                        }
                        break;
                    case 4:
                        if (float.TryParse(data[i], out val))
                        {
                            double temp = val;
                            graphTemp(temp, missionTimePayload);
                        }
                        break;
                    case 5:
                        if (float.TryParse(data[i], out val))
                        {
                            float volt = val;
                            graphVoltage(volt);
                        }
                        break;
                    case 6:
                        if (float.TryParse(data[i], out val))
                        {
                            angl.Add(val);
                        }
                        break;
                    case 7:
                        if (float.TryParse(data[i], out val))
                        {
                            angl.Add(val);
                        }
                        break;
                    case 8:
                        if (float.TryParse(data[i], out val))
                        {
                            angl.Add(val);
                            while (angl.Count < 3)
                                angl.Add(0);
                            graphAngleX(angl[0]);
                            graphAngleY(angl[1]);
                            graphAngleZ(angl[2]);
                        }                   
                        break;
                    case 9:
                        if (float.TryParse(data[i], out val))
                        {
                            acel.Add(val);
                        }
                        break;
                    case 10:
                        if (float.TryParse(data[i], out val))
                        {
                            acel.Add(val);
                        }
                        break;
                    case 11:
                        if (float.TryParse(data[i], out val))
                        {
                            acel.Add(val);
                            while (acel.Count < 3)
                                acel.Add(0);
                            graphAcceleration(acel, missionTimePayload);
                        }
                        break;
                    case 12:
                        if (float.TryParse(data[i], out val))
                        {
                            long pressure = (long)val;
                            graphPreassure(pressure, currentAlt, missionTimePayload);
                        }
                        break;

                }

            }

            addCsv(1, package);


        }

        /**Grafica los datos del  container guardados en un archivo**/
        public void readContainer(String package)
        {
            List<String> data = package.Split(',').ToList<String>();
            float val = 0;

            for (int i = 0; i < data.Count; i++)
            {
                switch (i)
                {
                    case 0:
                            lastTeamID = data[i];
                        break;
                    case 1:
                        if (float.TryParse(data[i], out val))
                        {
                            displayCountC((int)val);
                        }

                        break;
                    case 2:
                        if (float.TryParse(data[i], out val))
                        {
                            missionTimeContainer = (int)val;
                            displayTimeC(missionTimeContainer);
                        }
                        break;
                    case 3:
                        if (float.TryParse(data[i], out val))
                        {
                            double preasure = val;
                            double altitude = calcAltitude(preasure);
                            graphAltitud(altitude, missionTimeContainer);
                        }
                        break;
                }

            }

            addCsv(2, package);


        }

        /**Carga un CVS con datos del Payload**/
        public Boolean loadFileP(String fileName)
        {
            Boolean resp = true;
            StreamReader file;
            String line;

            try
            {
                file = new StreamReader(fileName);
                while ((line = file.ReadLine()) != null)
                {
                    readPayload(line);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
                resp = false;
            }

            return resp;
        }

        /**Carga un CVS con datos del Container**/
        public Boolean loadFileC(String fileName)
        {
            Boolean resp = true;
            StreamReader file;
            String line;

            try
            {
                file = new StreamReader(fileName);
                while ((line = file.ReadLine()) != null)
                {
                    readContainer(line);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
                resp = false;
            }

            return resp;
        }


        /*Envía mensaje al XBEE solicitando datos de test del Payload**/
        public Boolean requestP(int type)
        {
            Boolean resp = true;

            if (serialPort.IsOpen)
            {
                switch (type)
                {
                    case 0:
                        serialPort.Write("M");
                        expectingP = type;
                        break;
                    case 1:
                        serialPort.Write("T");
                        expectingP = type;
                        break;
                    case 2:
                        serialPort.Write("P");
                        expectingP = type;
                        break;
                    case 3:
                        serialPort.Write("V");
                        expectingP = type;
                        break;
                    case 4:
                        serialPort.Write("A");
                        expectingP = type;
                        break;
                    case 5:
                        serialPort.Write("C");
                        expectingP = type;
                        break;
                    case 6:
                        serialPort.Write("S");
                        expectingP = type;
                        break;
                    case 7:
                        serialPort.Write("X");
                        expectingP = type;
                        break;
                    case 8:
                        serialPort.Write("Y");
                        expectingP = type;
                        break;
                    case 9:
                        serialPort.Write("J");
                        expectingP = type;
                        break;
                    case 10:
                        serialPort.Write("K");
                        expectingP = type;
                        break;
                    case 11:
                        serialPort.Write("H");
                        expectingP = type;
                        break;
                    case 12:
                        serialPort.Write("O");
                        expectingP = type;
                        break;
                    case 13:
                        serialPort.Write("D");
                        expectingP = type;
                        break;
                    case 14:
                        serialPort.Write("I");
                        expectingP = type;
                        break;
                    case 15:
                        serialPort.Write("L");
                        expectingP = type;
                        break;
                    case 17:
                        serialPort.Write("H");
                        //expectingC = type;
                        break;
                    case INITCODE:
                        serialPort.Write("W" + waiting + ENDCHAR);
                        expectingC = type;
                        break;
                    case EXITCODE:
                        serialPort.Write("E");
                        expectingP = type;
                        break;
                    default:
                        expectingP = -1;
                        break;
                }

            }
            else
            {
                resp = false;
                expectingP = -1;
                MessageBox.Show("Connection with Payload lost");
            }

            return resp;
        }

        /*Envía mensaje al XBEE solicitando datos de test del Container**/
        public Boolean requestC(int type)
        {
            Boolean resp = true;

            if (serialPort2.IsOpen)
            {
                switch (type)
                {
                    case 0:
                        serialPort2.Write("M");
                        expectingC = type;
                        break;
                    case 1:
                        serialPort2.Write("P");
                        expectingC = type;
                        break;
                    case 2:
                        serialPort2.Write("C");
                        expectingC = type;
                        break;
                    case 3:
                        serialPort2.Write("S");
                        expectingC = type;
                        break;
                    case 4:
                        serialPort2.Write("J");
                        expectingC = type;
                        break;
                    case 5:
                        serialPort2.Write("K");
                        expectingC = type;
                        break;
                    case 6:
                        serialPort2.Write("H");
                        //expectingC = type;
                        expectingC = -1;
                        break;
                    case 7:
                        serialPort2.Write("O");
                        expectingC = type;
                        break;
                    case 8:
                        serialPort2.Write("D");
                        expectingC = type;
                        break;
                    case 9:
                        serialPort2.Write("I");
                        expectingC = type;
                        break;
                    case 11:
                        serialPort2.Write("X");
                        expectingC = type;
                        break;
                    case 12:
                        serialPort2.Write("Y");
                        expectingC = type;
                        break;
                    case EXITCODE:
                        serialPort2.Write("E");
                        expectingC = type;
                        break;
                    default:
                        expectingC = -1;
                        break;
                }

            }
            else
            {
                resp = false;
                expectingC = -1;
                MessageBox.Show("Connection with Container lost");
            }

            return resp;
        }

        /**Procesa la información recibida para testing**/
        private void addResponse(byte[] package, int source)
        {
            String cadena;
            int pos;

            if (source == 1)
            {
                lock (pendingP)
                {
                    pendingP += hexToStr(package);
                    pos = pendingP.IndexOf(ENDCHAR);

                    if (pos >= 0)
                    {

                        cadena = pendingP.Substring(0, pos);
                        if (pos < (pendingP.Length - 1))
                            pendingP = pendingP.Substring(pos + 1);
                        else
                            pendingP = "";
                        if ((cadena.Length > 0))
                        {
                            processTestP(cadena);
                        }
                    }

                }
            }
            else
            {
                lock (pendingC)
                {
                    pendingC += hexToStr(package);
                    pos = pendingC.IndexOf(ENDCHAR);

                    if (pos >= 0)
                    {

                        cadena = pendingC.Substring(0, pos);
                        if (pos < (pendingC.Length - 1))
                            pendingC = pendingC.Substring(pos + 1);
                        else
                            pendingC = "";
                        if ((cadena.Length > 0))
                        {
                            processTestC(cadena);
                        }
                        expectingC = -1;
                    }

                }
            }

        }

        /**Displays the test info in labels**/
        public void displayTest(Label destination, double val, String txt)
        {
            if (destination.InvokeRequired)
            {
                displayTestCallback call = new displayTestCallback(displayTest);
                this.Invoke(call, new object[] { destination, val, txt });
            }
            else
            {
                destination.Text = txt + val.ToString("#,##0.00");
            }
        }

        /**Display the packets received during testing**/
        public void displayTestP(String val)
        {
            if (listBoxTest.InvokeRequired)
            {
                displayTestPCallback call = new displayTestPCallback(displayTestP);
                this.Invoke(call, new object[] { val });
            }
            else
                listBoxTest.Items.Add(val);
                
        }

        /**Display the packets received during testing**/
        public void displayTestC(String val)
        {
            if (listBoxTest.InvokeRequired)
            {
                displayTestPCallback call = new displayTestPCallback(displayTestC);
                this.Invoke(call, new object[] { val });
            }
            else
                listBoxTest.Items.Add(val);

        }

        /**Muestra el resultado de los self tests**/
        public void testResult(PictureBox destination, int index)
        {

            if (destination.InvokeRequired)
            {
                testResultCallback call = new testResultCallback(testResult);
                this.Invoke(call, new object[] { destination, index });
            }
            else
                destination.Image = statusImg[index];

        }

        /**Muestra la información solicitada en el testing del payload**/
        public void processTestP(String data)
        {
            float val;
            switch (expectingP)
            {
                case 0:
                    if (data == "MONITOREO")
                        MessageBox.Show("Payload testing mode ON");
                    else
                    {
                        MessageBox.Show("Undefined message received: " + data);  
                    }
                    expectingP = -1; 
                    break;
                case 1:
                    if (float.TryParse(data, out val))
                    {
                        double disp = calcTemp((int)val);
                        displayTest(labelTTemperature, disp, "Last Temperature (°C): ");
                        resultsP[11] = disp.ToString("#,###,##0.00");
                        
                    }
                    else
                    {
                        MessageBox.Show("Undefined message received: " + data);
                    }
                    expectingP = -1; 
                    break;
                case 2:
                    if (float.TryParse(data, out val))
                    {
                        double disp = calcPreasure((int)val);
                        displayTest(labelTPreasure, disp, "Last Pressure (Pa): ");
                        resultsP[1] = disp.ToString("#,###,##0.00");
                    }
                    else
                    {
                        MessageBox.Show("Undefined message received: " + data);
                    }
                    expectingP = -1; 
                    break;
                case 3:
                    if (float.TryParse(data, out val))
                    {
                        double disp = calcVoltage(val);
                        displayTest(labelTVoltage, disp, "Last Voltage: (V): ");
                        resultsP[4] = disp.ToString("#,###,##0.00");
                    }
                    else
                    {
                        MessageBox.Show("Undefined message received: " + data);
                    }
                    expectingP = -1;
                    break;
                case 4:
                    List<long> acel = getAceleration(data);
                    for (int i = 0; i < acel.Count; i++)
                    {
                        if (i == 0)
                        {
                            displayTest(labelTX, acel[i], "X Acceleration (G): ");
                            resultsP[5] = acel[i].ToString("#,###,##0.00");
                        }
                        else if (i == 1)
                        {
                            displayTest(labelTY, acel[i], "Y Acceleration (G): ");
                            resultsP[6] = acel[i].ToString("#,###,##0.00");
                        }
                        else if (i == 2)
                        {
                            displayTest(labelTZ, acel[i], "Z Acceleration (G): ");
                            resultsP[7] = acel[i].ToString("#,###,##0.00");
                        }
                    }
                    expectingP = -1; 
                    break;
                case 5:
                    if (float.TryParse(data, out val))
                    {
                        displayTest(labelTime, val, "Last Mission Time(s): ");
                        resultsP[12] = val.ToString("#,###,##0.00");

                    }
                    else
                    {
                        MessageBox.Show("Undefined message received: " + data);
                    }
                    expectingP = -1;
                    break;
                case 6:
                    if (float.TryParse(data, out val))
                    {
                        displayTest(labelPackets, val, "Last Packet Count:");
                        resultsP[13] = val.ToString("#,###,##0.00");
                    }
                    else
                    {
                        MessageBox.Show("Undefined message received: " + data);
                    }
                    expectingP = -1;
                    break;
                case 7:
                    displayTestP(data);
                    expectingP = -1;
                    break;
                case 8:
                    displayTestP(data);
                    expectingP = -1;
                    break;
                case 9:
                    displayTestP(data);
                    expectingP = -1;
                    break;
                case 10:
                    displayTestP(data);
                    expectingP = -1;
                    break;
                case 11:
                    displayTestP(data);
                    expectingP = -1;
                    break;
                case 12:
                    if (data.IndexOf(ENDBULK) >= 0)
                    {
                        data = data.Substring(0, data.Length - 1);
                        expectingP = -1;
                    }
                    displayTestP(data);
                    break;
                case 13:
                    if (data == "A")
                        MessageBox.Show("Undefined message received: " + data);
                    expectingP = -1;
                    break;
                case 14:
                    if (data == "SUCCESS")
                        MessageBox.Show("Payload's memory succesfully initialized");
                    else
                    {
                        MessageBox.Show("Undefined message received: " + data);  
                    }
                    expectingP = -1;
                    break;
                case 15:
                    if (data.Length < 1)
                        MessageBox.Show("Undefined message received: " + data);
                    testAcel = data;
                    expectingP = 16;
                    break;
                case 16:
                    List<long> first = getAceleration(testAcel);
                    List<long> second = getAceleration(data);

                    double promx1 = 0;
                    double promy1 = 0;
                    double promz1 = 0;
                    double promx2 = 0;
                    double promy2 = 0;
                    double promz2 = 0;

                    int cantx1 = 0;
                    int canty1 = 0;
                    int cantz1 = 0;
                    int cantx2 = 0;
                    int canty2 = 0;
                    int cantz2 = 0;

                    for (int i = 0; i < first.Count; i++)
                    {
                        if ((i % 3) == 0)
                        {
                            promx1 += first[i];
                            cantx1++;
                        }
                        else if ((i % 2) == 0)
                        {
                            promz1 += first[i];
                            cantz1++;
                        }
                        else if ((i % 1) == 0)
                        {
                            promy1 += first[i];
                            canty1++;
                        }
                        
                    }

                    if (cantx1 > 0)
                        promx1 = (promx1 / cantx1);
                    if (canty1 > 0)
                        promy1 = (promy1 / canty1);
                    if (cantz1 > 0)
                        promz1 = (promz1 / cantz1);

                    for (int i = 0; i < second.Count; i++)
                    {
                        if ((i % 3) == 0)
                        {
                            promx2 += second[i];
                            cantx2++;
                        }
                        else if ((i % 2) == 0)
                        {
                            promz2 += second[i];
                            cantz2++;
                        }
                        else if ((i % 1) == 0)
                        {
                            promy2 += second[i];
                            canty2++;
                        }
                        
                    }

                    if (cantx2 > 0)
                        promx2 = (promx2 / cantx2);
                    if (canty2 > 0)
                        promy2 = (promy2 / canty2);
                    if (cantz2 > 0)
                        promz2 = (promz2 / cantz2);

                    promz2 = -1 * promz2;
                    promz1 = -1 * promz1;

                    if (((promx2 - promx1) >= (MINDX * 1.77)) && ((promx2 - promx1) <= (MAXDX * 1.77)))
                    {
                        buttonSelfAcelX.BackColor = Color.Green;
                        resultsP[14] = "Passed";
                    }
                    else
                    {
                        buttonSelfAcelX.BackColor = Color.Red;
                        resultsP[14] = "Failed";
                    }

                    if (((promy2 - promy1) >= (MINDY * 1.77)) && ((promy2 - promy1) <= (MAXDY * 1.77)))
                    {
                        buttonSelfAcelY.BackColor = Color.Green;
                        resultsP[15] = "Passed";
                    }
                    else
                    {
                        buttonSelfAcelY.BackColor = Color.Red;
                        resultsP[15] = "Failed";
                    }
                    if (((promz2 - promz1) >= (MINDZ * 1.47)) && ((promz2 - promz1) <= (MAXDZ * 1.47)))
                    {
                        buttonSelfAcelZ.BackColor = Color.Green;
                        resultsP[16] = "Passed";
                    }
                    else
                    {
                        buttonSelfAcelZ.BackColor = Color.Red;
                        resultsP[16] = "Failed";
                    }

                    expectingP = -1;
                    break;
                case EXITCODE:
                    MessageBox.Show("Ending transmission for Payload");
                    if (data != "ADIOS")
                    {
                        MessageBox.Show("Undefined message received: " + data);
                    }
                    expectingP = -1;
                    mode = -1;
                    serialPort.Close();
                    break;


            }
        }

        /**Muestra la información solicitada en el testing del container**/
        public void processTestC(String data)
        {
            float val;
            switch (expectingC)
            {
                case 0:
                    if (data == "MONITOREO")
                        MessageBox.Show("Container testing mode ON");
                    else
                    {
                        MessageBox.Show("Undefined message received: " + data);
                    }
                    expectingC = -1;
                    break;
                case 1:
                    if (float.TryParse(data, out val))
                    {
                        double pressure = calcPressureC((int)val);
                        double altitude = calcAltitude(pressure);
                        displayTest(labelTPreasureC, pressure, "Last Pressure (Pa): ");
                        displayTest(labelTAltitudeC, altitude, "Last Altitude (m): ");
                        resultsC[1] = pressure.ToString("#,###,##0.00");
                        resultsC[2] = altitude.ToString("#,###,##0.00");

                    }
                    else
                    {
                        MessageBox.Show("Undefined message received: " + data);
                    }
                    expectingC = -1;
                    break;
                case 2:
                    if (float.TryParse(data, out val))
                    {
                        displayTest(labelTTimeC, val, "Last Mission Time (s): ");
                        resultsC[3] = val.ToString("#,###,##0.00");
                    }
                    else
                    {
                        MessageBox.Show("Undefined message received: " + data);
                    }
                    expectingC = -1;
                    break;
                case 3:
                   if (float.TryParse(data, out val))
                    {
                        displayTest(labelTPacketC, val, "Last PacketCount: ");
                        resultsC[4] = val.ToString("#,###,##0.00");
                    }
                    else
                    {
                        MessageBox.Show("Undefined message received: " + data);
                    }
                    expectingC = -1;
                    break;
                case 4:
                    displayTestP(data);
                    expectingC = -1;
                    break;
                case 5:
                    displayTestP(data);
                    expectingC = -1;
                    break;
                case 6:
                    displayTestP(data);
                    expectingC = -1;
                    break;
                case 7:
                    if (data.IndexOf(ENDBULK) >= 0)
                    {
                        data = data.Substring(0, data.Length - 1);
                        expectingC = -1;
                    }
                    displayTestC(data);
                    break;
                case 8:
                    if (data.Length > 0)
                        MessageBox.Show("Undefined message received: " + data);
                    expectingC = -1;
                    break;
                case 9:
                    if (data == "A")
                        MessageBox.Show("Memory initialized succesfuly");
                    else
                    {
                        MessageBox.Show("Undefined message received: " + data);
                    }
                    expectingC = -1;
                    break;
                case EXITCODE:
                    MessageBox.Show("Ending transmission for Container");
                    if (data != "ADIOS")
                    {
                        MessageBox.Show("Undefined message received: " + data);
                    }
                    expectingC = -1;
                    mode = -1;
                    serialPort2.Close();
                    break;


            }
        }

        /**Agrega un paquete a su respectivo formato CSV**/
        public void addCsv(int dest, String line)
        {
            if (dest == 1)
            {
                if (listCsvPacketsP.InvokeRequired)
                {
                    addCsvCallback call = new addCsvCallback(addCsv);
                    this.Invoke(call, new object[] { dest, line });
                }
                else
                    listCsvPacketsP.Items.Add(line);
                
            }
            else
            {
                if (listCsvPacketsC.InvokeRequired)
                {
                    addCsvCallback call = new addCsvCallback(addCsv);
                    this.Invoke(call, new object[] { dest, line });
                }
                else
                    listCsvPacketsC.Items.Add(line);
            }
        }

        /**Confirmación de conexión con Container**/
        private void checkConfirmation(byte[] package)
        {
            String cadena;
            int pos;

            lock (pendingF)
            {
                pendingF += hexToStr(package);
                pos = pendingF.IndexOf(ENDCHAR);

                while (pos >= 0)
                {

                    cadena = pendingF.Substring(0, pos);
                    if (pendingF.Length > 1)
                        pendingF = pendingF.Substring(pos + 1);
                    else
                        pendingF = "";


                    if (cadena == "OK")
                        showConfirmation(DateTime.Now.ToString("h:mm:ss tt"));
                   // else
                     //   MessageBox.Show("Unidefined message received " + cadena);

                    pos = pendingF.IndexOf(ENDCHAR);
                }

            }

        }

        /**Muestra mensaje de confirmación**/
        private void showConfirmation(String time)
        {
            if (labelConnected.InvokeRequired)
            {
                ShowConfirmationCallback call = new ShowConfirmationCallback(showConfirmation);
                this.Invoke(call, new object[] { time });
            }
            else
                labelConnected.Text = "Last connected: " + time;
        }

        /**Inicializa las variables para tests**/
        public void initTests()
        {
            resultsP = new List<string>();
            resultsC = new List<string>();
            namesTC = new List<string>();
            namesTP = new List<string>();

            namesTP.Add("Pressure state: ");
            namesTP.Add("Pressure obtained: ");
            namesTP.Add("Altitude obtained: ");
            namesTP.Add("Voltage state: ");
            namesTP.Add("Voltage obtained: ");
            namesTP.Add("Axis state: ");
            namesTP.Add("X acceleration obtained: ");
            namesTP.Add("Y acceleration obtained: ");
            namesTP.Add("Z acceleration obtained: ");
            namesTP.Add("Angle obtained: ");
            namesTP.Add("Temperature state: ");
            namesTP.Add("Temperature obtained: ");
            namesTP.Add("Mission time obtained: ");
            namesTP.Add("Packet count obtained: ");
            namesTP.Add("Axis X self test result: ");
            namesTP.Add("Axis Y self test result: ");
            namesTP.Add("Axis Z self test result: ");

            namesTC.Add("Pressure state: ");
            namesTC.Add("Pressure obtained: ");
            namesTC.Add("Altitude obtained: ");
            namesTC.Add("Mission time obtained: ");
            namesTC.Add("Packet count obtained: ");

            for (int i = 0; i < namesTP.Count; i++)
            {
                resultsP.Add("n/a");
            }

            for (int i = 0; i < namesTC.Count; i++)
            {
                resultsC.Add("n/a");
            }

            sensorSet = 0;
           
        }

        #endregion


        public Form1()
        {
            InitializeComponent();
            //chartVoltage.ChartAreas[0].AxisY.Minimum = 0;
            //chartVoltage.ChartAreas[0].AxisY.Maximum = 4096;
            //chartAltitudeP.ChartAreas[0].AxisY.Minimum = 0;
            //chartAltitudeP.ChartAreas[0].AxisY.Maximum = 1500;
            //chartPreassureTemp.ChartAreas[0].AxisY.Minimum = 84700;
            //chartPreassureTemp.ChartAreas[0].AxisY.Maximum = 85200;
            //chartTemp.ChartAreas[0].AxisY.Minimum = 20;
            //chartTemp.ChartAreas[0].AxisY.Maximum = 40;
            chartAltitudeC.ChartAreas[0].AxisY.Minimum = 450;
            chartAltitudeC.ChartAreas[0].AxisY.Maximum = 1100;
        }

        private void label3_Click(object sender, EventArgs e)
        {

        }

        private void label2_Click(object sender, EventArgs e)
        {

        }

        private void label8_Click(object sender, EventArgs e)
        {

        }

        private void chart3_Click(object sender, EventArgs e)
        {

        }

        private void Form1_Load(object sender, EventArgs e)
        {
            //file = null;
            mode = -1;
            expectingP = -1;
            expectingC = -1;
            pendingF = "";
            pendingP = "";
            pendingC = "";
            fileC = null;
            fileP = null;
            statusImg = new Image[3];
            statusImg[0] = Image.FromFile("none.png");
            statusImg[1] = Image.FromFile("passed.png");
            statusImg[2] = Image.FromFile("Failed.png");
            /*chartResAltitude.ChartAreas[0].AxisX.Minimum = 0;
            chartResAltitude.ChartAreas[0].AxisX.Maximum = 5;
            chartResPressure.ChartAreas[0].AxisY.Minimum = 0;
            chartResPressure.ChartAreas[0].AxisY.Maximum = 400;
            chartResPressure.ChartAreas[0].AxisX.Minimum = 0;
            chartResPressure.ChartAreas[0].AxisX.Maximum = 5;
            chartResVoltage.ChartAreas[0].AxisX.Minimum = 0;
            chartResVoltage.ChartAreas[0].AxisX.Maximum = 5;
            chartResTemperature.ChartAreas[0].AxisX.Minimum = 0;
            chartResTemperature.ChartAreas[0].AxisX.Maximum = 5;*/


            chartAngleX.ChartAreas[0].AxisY.LabelStyle.Enabled = false;


        }

        private void button2_Click(object sender, EventArgs e)
        {
            requestP(17);
            

        }

        public void pruebaGraf(float val1, float val2,float val3,float val4)
        {

        }

        private void timerRandom_Tick(object sender, EventArgs e)
        {

            Random rand = new Random();
            countP++;

            float val1 = rand.Next(150);
            float val2 = rand.Next(400);
            float val3 = rand.Next(1450);
            float val4 = rand.Next(620);

            pruebaGraf(val1, val2, val3, val4);
            


        }

        private void button1_Click(object sender, EventArgs e)
        {
            string[] ports;
            int pos;
            CustomMessage dialogo;

            if (mode != -1)
            {
                if (mode == 5)
                {
                    //FLIGHT MODE
                    if (comboModes.SelectedIndex == 1)
                {


                        initTrans();
                        prompt message = new prompt("Waiting Value", "Seconds to wait:", 1, 9999);
                        message.ShowDialog();
                        mode = 1;
                        waiting = message.value;

                        while (waiting.Length < 4)
                            waiting = "0" + waiting;

                        try
                        {
                            serialPort.DiscardInBuffer();
                            requestP(INITCODE);
                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show(ex.ToString());
                        }

                       // buttonStop.Visible = true;
                        labelConnected.Visible = false;
                        //buttonSaveAll.Visible = true;
                        //buttonSaveCsv.Visible = true;
                        listReceivedPacketsContainer.Visible = true;
                        listReceivedPacketsPayload.Visible = true;
                        listCsvPacketsC.Visible = false;
                        listCsvPacketsP.Visible = false;
                    
                }
                }
                else
                    MessageBox.Show("There already is one transmission in course");
            }
            else
            {

                //CARGAR DESDE ARCHIVO CSV
                if (comboModes.SelectedIndex == 2)
                {
                    initTrans();
                    if (fileP != null)
                        loadFileP(fileP);
                    if (fileC != null)
                        loadFileC(fileC);
                   // buttonSaveAll.Visible = true;
                    //buttonSaveCsv.Visible = true;
                    //buttonStop.Visible = true;

                    listReceivedPacketsContainer.Visible = false;
                    listReceivedPacketsPayload.Visible = false;
                    listCsvPacketsC.Visible = true;
                    listCsvPacketsP.Visible = true;

                }
                    //GROUND TEST
                else if (comboModes.SelectedIndex == 0)
                {

                    prompt selSet;

                    initTests();

                    selSet = new prompt("Select Pressure Sensor", "Pressure sensor #:", 1, 2);
                    selSet.ShowDialog();

                    if (selSet.value == "")
                    {
                        MessageBox.Show("Connection to CanSat canceled");
                    }
                    else
                    {

                        sensorSet = Convert.ToInt32(selSet.value);

                        ports = SerialPort.GetPortNames();
                        dialogo = new CustomMessage("Communication Port Payload", ports);


                        dialogo.customShow();
                        pos = dialogo.getPuerto();
                        if (pos > -1)
                        {
                            mode = comboModes.SelectedIndex;
                            expectingP = 0;
                            synTemp = new object();
                            tabControl1.SelectedTab = pageTest;
                            portName = ports[pos];
                            serialPort.PortName = portName;
                            serialPort.BaudRate = 9600;
                            serialPort.Open();
                            MessageBox.Show("Payload connected to port " + portName);
                            try
                            {
                                serialPort.DiscardInBuffer();
                            }
                            catch (Exception ex)
                            {
                                MessageBox.Show(ex.ToString());
                            }
                            requestP(0);

                        }
                        else
                        {
                            portName = "";
                            MessageBox.Show("Payload not connected");
                        }

                        ports = SerialPort.GetPortNames();
                        dialogo = new CustomMessage("Communication Port Container", ports);


                        dialogo.customShow();
                        pos = dialogo.getPuerto();
                        if (pos > -1)
                        {
                            mode = comboModes.SelectedIndex;
                            expectingC = 0;
                            synTemp = new object();
                            tabControl1.SelectedTab = pageTest;
                            portName = ports[pos];
                            serialPort2.PortName = portName;
                            serialPort2.BaudRate = 9600;
                            serialPort2.Open();
                            MessageBox.Show("Container connected to port " + portName);
                            try
                            {
                                serialPort2.DiscardInBuffer();
                            }
                            catch (Exception ex)
                            {
                                MessageBox.Show(ex.ToString());
                            }
                            requestC(0);

                            buttonStop.Visible = true;
                            //buttonSaveAll.Visible = false;
                            buttonSaveCsv.Visible = true;

                            listReceivedPacketsContainer.Visible = true;
                            listReceivedPacketsPayload.Visible = true;
                            listCsvPacketsC.Visible = false;
                            listCsvPacketsP.Visible = false;

                        }
                        else
                        {
                            portName = "";
                            MessageBox.Show("Container not connected");
                        }
                    }


                }
                    //CARGAR DESDE MEMORIA DE PAYLOAD Y CONTAINER
                else if (comboModes.SelectedIndex == 3)
                {

                    prompt selSet;

                    initTrans();

                    selSet = new prompt("Select Pressure Sensor", "Pressure sensor #:", 1, 2);
                    selSet.ShowDialog();

                    if (selSet.value == "")
                    {
                        MessageBox.Show("Connection to CanSat canceled");
                    }
                    else
                    {

                        sensorSet = Convert.ToInt32(selSet.value) - 1;

                        ports = SerialPort.GetPortNames();
                        dialogo = new CustomMessage("Communication Port", ports);

                        dialogo.customShow();
                        pos = dialogo.getPuerto();
                        if (pos > -1)
                        {
                            initTrans();

                            portName = ports[pos];
                            serialPort.PortName = portName;
                            serialPort.BaudRate = 9600;
                            serialPort.Open();
                            mode = comboModes.SelectedIndex;
                            //expectingC = INITCODE;
                            MessageBox.Show("Connected to port " + portName);

                            try
                            {
                                serialPort.DiscardInBuffer();
                                requestP(0);
                                expectingP = 0;
                            }
                            catch (Exception ex)
                            {
                                MessageBox.Show(ex.ToString());
                            }

                            buttonStop.Visible = true;
                           // buttonSaveAll.Visible = false;
                            //buttonSaveCsv.Visible = false;

                            listReceivedPacketsContainer.Visible = true;
                            listReceivedPacketsPayload.Visible = true;
                            listCsvPacketsC.Visible = false;
                            listCsvPacketsP.Visible = false;


                        }
                        else
                        {
                            portName = "";
                            MessageBox.Show("Not connected");
                        }
                    }



                }
                else
                    MessageBox.Show("Choose the data connection mode");
            }



        }

        private void serialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            byte[] data = new byte[serialPort.BytesToRead];
            serialPort.Read(data, 0, data.Length);

            if (mode == 1)
            {
               
                addPackage(data);
            }
            else if (mode == 0)
            {
                if (expectingP!=-1)
                {
                    addResponse(data, 1);   
                }
            }
            else if (mode == 3)
            {

                addPackage(data);
            }
            else if (mode == 5)
            {
                checkConfirmation(data);
            }

            
        }

        private void button4_Click(object sender, EventArgs e)
        {
            //GROUND TEST
            if (mode == 0)
            {
                if (serialPort.IsOpen)
                {
                    requestP(EXITCODE);
                    mode = -1;
                    expectingP = -1;
                    serialPort.Close();
                }
                if (serialPort2.IsOpen)
                {
                    requestC(EXITCODE);
                    mode = -1;
                    expectingC = -1;
                    serialPort2.Close();
                }
                //buttonStop.Visible = false;
                buttonSaveCsv.Visible = true;
               // buttonSaveAll.Visible = false;

            }
            //FLIGHT MODE
            else if (mode == 1)
            {
                if (serialPort.IsOpen)
                {
                    mode = -1;
                    serialPort.Close();
                    MessageBox.Show("Transmission terminated");
                }

                buttonSaveAll.Visible = true;
                buttonSaveCsv.Visible = true;
                //buttonStop.Visible = false;

            }
            else if (mode == 3)
            {
                if (serialPort.IsOpen)
                {
                    requestP(EXITCODE);
                    mode = -1;
                    expectingP = -1;
                    serialPort.Close();
                }
                if (serialPort2.IsOpen)
                {
                    requestC(EXITCODE);
                    mode = -1;
                    expectingC = -1;
                    serialPort2.Close();
                }
                //buttonStop.Visible = false;
                buttonSaveCsv.Visible = true;
                buttonSaveAll.Visible = true;

            }
            else if (mode == 2)
                mode = -1;

            labelConnected.Visible = false;
            //buttonStop.Visible = false;

        }

        private void button5_Click(object sender, EventArgs e)
        {

            StreamWriter file;
            if (mode == 0)
            {
                saveCSVDialog.FileName = "Tests results.csv";
                if (saveCSVDialog.ShowDialog() == DialogResult.OK)
                {
                    file = new StreamWriter(saveCSVDialog.FileName);
                    
                    file.Write("PAYLOAD\n");

                    for (int i = 0; i < resultsP.Count; i++)
                    {
                        file.Write(namesTP[i] + "," + resultsP[i] + "\n");
                    }

                    file.Write("\nCONTAINER\n");

                    for (int i = 0; i < resultsC.Count; i++)
                    {
                        file.Write(namesTC[i] + "," + resultsC[i] + "\n");
                    }

                    file.Close();

                }
                else
                    MessageBox.Show("Tests' results not saved");
            }
            else
            {
                saveCSVDialog.FileName = "CANSAT2014_TLM_" + TEAMID + "_EkUVG.csv";

                if (saveCSVDialog.ShowDialog() == DialogResult.OK)
                {
                    file = new StreamWriter(saveCSVDialog.FileName);

                    for (int i = 0; i < listCsvPacketsP.Items.Count; i++)
                    {
                        file.Write(listCsvPacketsP.Items[i].ToString() + "\n");
                    }

                    file.Close();

                    MessageBox.Show("File with Payload's telemetry saved succesfully at '" + saveCSVDialog.FileName + "'");
                }
                else
                    MessageBox.Show("File with Payload's telemetry wasn't saved");

                saveCSVDialog.FileName = "CANSAT2014_CAN_" + TEAMID + "_EkUVG.csv";

                if (saveCSVDialog.ShowDialog() == DialogResult.OK)
                {
                    file = new StreamWriter(saveCSVDialog.FileName);

                    for (int i = 0; i < listCsvPacketsC.Items.Count; i++)
                    {
                        file.Write(listCsvPacketsC.Items[i].ToString() + "\n");
                    }

                    file.Close();

                    MessageBox.Show("File with Container's telemetry saved succesfully at '" + saveCSVDialog.FileName + "'");
                }
                else
                    MessageBox.Show("File with Container's telemetry wasn't saved");
            }

        }

        private void buttonSaveAll_Click(object sender, EventArgs e)
        {
            StreamWriter csv;
            String msg = "";
            Boolean error = false;


            if (saveAllDialog.ShowDialog() == DialogResult.OK)
            {
                

                if (!Directory.Exists(saveAllDialog.SelectedPath + @"\Payload"))
                {
                    try
                    {
                        Directory.CreateDirectory(saveAllDialog.SelectedPath + @"\Payload");
                    }
                    catch (Exception ex)
                    {
                        msg += ex.ToString() + '\n';
                        error = true;
                    }
                }
                if (!Directory.Exists(saveAllDialog.SelectedPath + @"\Container"))
                {
                    try
                    {
                        Directory.CreateDirectory(saveAllDialog.SelectedPath + @"\Container");
                    }
                    catch (Exception ex)
                    {
                        msg += ex.ToString() + '\n';
                        error = true;
                    }
                }

                try
                {
                    chartAltitudeP.SaveImage(saveAllDialog.SelectedPath + @"\Payload\altitudvstime.png", System.Drawing.Imaging.ImageFormat.Png);
                    chartPreassureTemp.SaveImage(saveAllDialog.SelectedPath + @"\Payload\preassuretmpvstime.png", System.Drawing.Imaging.ImageFormat.Png);
                    chartVoltage.SaveImage(saveAllDialog.SelectedPath + @"\Payload\voltagevstime.png", System.Drawing.Imaging.ImageFormat.Png);
                    chartAltitudeC.SaveImage(saveAllDialog.SelectedPath + @"\Container\altitudvstime.png", System.Drawing.Imaging.ImageFormat.Png);
                    chartAccel.SaveImage(saveAllDialog.SelectedPath + @"\Payload\aceleration.png", System.Drawing.Imaging.ImageFormat.Png);
                    chartTemp.SaveImage(saveAllDialog.SelectedPath + @"\Payload\temperature.png", System.Drawing.Imaging.ImageFormat.Png);
                    chartAngleX.SaveImage(saveAllDialog.SelectedPath + @"\Payload\angleX.png", System.Drawing.Imaging.ImageFormat.Png);
                    chartAngleY.SaveImage(saveAllDialog.SelectedPath + @"\Payload\angleY.png", System.Drawing.Imaging.ImageFormat.Png);
                    chartAngleZ.SaveImage(saveAllDialog.SelectedPath + @"\Payload\angleZ.png", System.Drawing.Imaging.ImageFormat.Png);
                
                }
                catch (Exception ex)
                {
                    msg += ex.ToString() + '\n';
                    error = true;
                }

                csv = new StreamWriter(saveAllDialog.SelectedPath + @"\Payload\CANSAT2014_TLM_" + TEAMID + "_EkUVG.csv");
                for (int i = 0; i < listCsvPacketsP.Items.Count; i++)
                {
                    try
                    {
                        csv.Write(listCsvPacketsP.Items[i].ToString() + "\n");
                    }
                    catch (Exception ex)
                    {
                        msg += ex.ToString() + '\n';
                        error = true;
                    }
                }

                csv.Close();

                csv = new StreamWriter(saveAllDialog.SelectedPath + @"\Container\CANSAT2014CAN_" + TEAMID + "_EkUVG.csv");
                for (int i = 0; i < listCsvPacketsC.Items.Count; i++)
                {
                    try
                    {
                        csv.Write(listCsvPacketsC.Items[i].ToString() + "\n");
                    }
                    catch (Exception ex)
                    {
                        msg += ex.ToString() + '\n';
                        error = true;
                    }
                }

                csv.Close();

                if (error)
                    MessageBox.Show("There were some errors when saving the files:\n" + msg);

                

            }

        }

        private void chart5_Click(object sender, EventArgs e)
        {

        }

        private void comboModes_SelectedIndexChanged(object sender, EventArgs e)
        {

            if (comboModes.SelectedIndex == 2)
            {
                openCSVDialog.Title = "Payload Telemetry";
                if (openCSVDialog.ShowDialog() == DialogResult.OK)
                {
                    fileP = openCSVDialog.FileName;

                }
                else
                    fileP = null;

                openCSVDialog.Title = "Container Telemetry";
                if (openCSVDialog.ShowDialog() == DialogResult.OK)
                {
                    fileC = openCSVDialog.FileName;
                    
                }
                else
                    fileC = null;
                buttonStart.Visible = true;
                buttonConnect.Visible = false;

            }
            else if (comboModes.SelectedIndex == 1)
            {
                    //buttonStart.Visible = false;
                buttonConnect.Visible = true;
            }
            else
            {
                buttonStart.Visible = true;
                buttonConnect.Visible = false;
            }

        }

        private void openCSVDialog_FileOk(object sender, CancelEventArgs e)
        {

        }

        private void label6_Click(object sender, EventArgs e)
        {

        }

        private void panel2_Paint(object sender, PaintEventArgs e)
        {

        }

        private void buttonTestP_Click(object sender, EventArgs e)
        {
            Boolean resp, doRequest = false;

            if (mode == 0)
            {
                if (expectingP != -1)
                {
                    if (MessageBox.Show("You must wait until the last requested data to the Payload is received, do you want to send the signal anyways?", "Waiting for response", MessageBoxButtons.YesNo) == DialogResult.Yes)
                        doRequest = true;
                }
                else
                    doRequest = true;

                if (doRequest)
                {
                    try
                    {
                        serialPort.DiscardInBuffer();
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.ToString());
                    }

                    if (radioButtonTemperature.Checked)
                        resp = requestP(1);
                    else if (radioButtonPreasure.Checked)
                        resp = requestP(2);
                    else if (radioButtonVoltage.Checked)
                        resp = requestP(3);
                    else if (radioButtonAxis.Checked)
                        resp = requestP(4);
                    else if (radioButtonTime.Checked)
                        resp = requestP(5);
                    else if (radioButtonPackets.Checked)
                        resp = requestP(6);
                    else if (radioButtonInitP.Checked)
                        resp = requestP(14);
                    else if (radioButtonSelfTest.Checked)
                        resp = requestP(15);
                    else
                    {
                        expectingP = -1;
                        resp = false;
                    }

                    if (resp)
                        pendingP = "";

                }
            }
            else
            {
                MessageBox.Show("You must start the Ground Test mode first");
            }

        }

        private void comboModes_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
                button1_Click(sender, e);
        }

        private void pictureLeft_Click(object sender, EventArgs e)
        {

            Boolean resp, doRequest = false;

            if (mode == 0)
            {
                if (expectingC != -1)
                {
                    if (MessageBox.Show("You must wait until the last requested data to the Container is received, do you want to send the signal anyways?", "Waiting for response", MessageBoxButtons.YesNo) == DialogResult.Yes)
                        doRequest = true;
                }
                else
                    doRequest = true;

                if (doRequest)
                {
                    try
                    {
                        serialPort2.DiscardInBuffer();
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.ToString());
                    }

                    resp = requestC(11);
                    expectingC = -1;

                    if (resp)
                        pendingC = "";

                }
               
            }
            else
            {
                MessageBox.Show("You must start the Ground Test mode first");
            }

        }

        private void pictureRight_Click(object sender, EventArgs e)
        {
            Boolean resp, doRequest = false;

            if (mode == 0)
            {
                if (expectingC != 1)
                {
                    if (MessageBox.Show("You must wait until the last requested data to the Payload is received, do you want to send the signal anyways?", "Waiting for response", MessageBoxButtons.YesNo) == DialogResult.Yes)
                        doRequest = true;
                }
                else
                    doRequest = true;

                if (doRequest)
                {
                    try
                    {
                        serialPort2.DiscardInBuffer();
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.ToString());
                    }

                    resp = requestC(12);
                    expectingC = -1;

                    if (resp)
                        pendingC = "";

                }

            }
            else
            {
                MessageBox.Show("You must start the Ground Test mode first");
            }
        }

        private void serialPort2_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            byte[] data = new byte[serialPort2.BytesToRead];
            serialPort2.Read(data, 0, data.Length);

            if (mode == 0)
            {
                if (expectingC != -1)
                {
                    addResponse(data, 2);
                }
            }
            
        }

        private void buttonTestC_Click(object sender, EventArgs e)
        {
            Boolean resp, doRequest = false;

            if (mode == 0)
            {
                if (expectingC!= -1)
                {
                    if (MessageBox.Show("You must wait until the last requested data to the Container is received, do you want to send the signal anyways?", "Waiting for response", MessageBoxButtons.YesNo) == DialogResult.Yes)
                        doRequest = true;
                }
                else
                    doRequest = true;

                if (doRequest)
                {
                    try
                    {
                        serialPort2.DiscardInBuffer();
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.ToString());
                    }

                    
                    if (radioButtonPreasureC.Checked)
                        resp = requestC(1);
                    else if (radioButtonTimeC.Checked)
                        resp = requestC(2);
                    else if (radioButtonFPacketC.Checked)
                        resp = requestC(3);
                    else if (radioButtonInitC.Checked)
                        resp = requestC(9);
                    else
                    {
                        expectingP = -1;
                        resp = false;
                    }

                    if (resp)
                        pendingP = "";

                }

            }
            else
            {
                MessageBox.Show("You must start the Ground Test mode first");
            }
        }

        private void radioButtonPInit_CheckedChanged(object sender, EventArgs e)
        {

        }

        private void buttonMemory_Click(object sender, EventArgs e)
        {

            Boolean resp, doRequest = false;

            if (mode == 0)
            {
                if (expectingC!= -1)
                {
                    if (MessageBox.Show("You must wait until the last requested data to the Container is received, do you want to send the signal anyways?", "Waiting for response", MessageBoxButtons.YesNo) == DialogResult.Yes)
                        doRequest = true;
                }
                else
                    doRequest = true;

                if (doRequest)
                {
                    if ((radioButtonPacketP.Checked) || (radioButtonSaveP.Checked) || (radioButtonSaveXP.Checked) || (radioButtonEraseP.Checked) || (radioButtonReadP.Checked))
                    {
                        try
                        {
                            serialPort.DiscardInBuffer();
                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show(ex.ToString());
                        }
                    }
                    else if ((radioButtonCPacket.Checked) || (radioButtonSaveC.Checked) || (radioButtonSaveXC.Checked) || (radioButtonEraseC.Checked) || (radioButtonReadC.Checked))
                    {
                        try
                        {
                            serialPort2.DiscardInBuffer();
                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show(ex.ToString());
                        }
                    }


                    if (radioButtonPacketP.Checked)
                        resp = requestP(9);
                    else if (radioButtonSaveP.Checked)
                        resp = requestP(10);
                    else if (radioButtonSaveXP.Checked)
                        resp = requestP(11);
                    else if (radioButtonReadP.Checked)
                        resp = requestP(12);
                    else if (radioButtonEraseP.Checked)
                        resp = requestP(13);
                    else if (radioButtonCPacket.Checked)
                        resp = requestC(4);
                    else if (radioButtonSaveC.Checked)
                        resp = requestC(5);
                    else if (radioButtonSaveXC.Checked)
                        resp = requestC(6);
                    else if (radioButtonReadC.Checked)
                        resp = requestC(7);
                    else if (radioButtonEraseC.Checked)
                        resp = requestC(8);

                }
                
            }
            else
                MessageBox.Show("You must start the Ground Test mode first");


        }

        private void buttonSelfTest_Click(object sender, EventArgs e)
        {
            

        }

        private void pageTest_Click(object sender, EventArgs e)
        {

        }

        private void panel7_Paint(object sender, PaintEventArgs e)
        {



        }

        private void labelClean_Click(object sender, EventArgs e)
        {
            listBoxTest.Items.Clear();
        }

        private void panelTestPayload_Paint(object sender, PaintEventArgs e)
        {

        }

        private void button4_Click_1(object sender, EventArgs e)
        {


            /*countP = 0;
            if (timerRandom.Enabled)
                timerRandom.Enabled = false;
            else
                timerRandom.Enabled = true;*/
        }

        private void buttonResPresU_Click(object sender, EventArgs e)
        {

        }

        private void buttonResPresD_Click(object sender, EventArgs e)
        {

        }

        private void comboModes_SelectedValueChanged(object sender, EventArgs e)
        {

        }

        private void buttonPassPress_Click(object sender, EventArgs e)
        {
            trackBarPressTest.Value = 0;
            resultsP[0] = "Passed";
        }

        private void buttonFailPress_Click(object sender, EventArgs e)
        {
            trackBarPressTest.Value = 1;
            resultsP[0] = "Failed";
        }

        private void buttonPassAcel_Click(object sender, EventArgs e)
        {
            trackBarAcelTest.Value = 0;
        }

        private void buttonFailAcel_Click(object sender, EventArgs e)
        {
            trackBarAcelTest.Value = 1;
        }

        private void buttonConnect_Click(object sender, EventArgs e)
        {
            string[] ports;
            int pos;
            CustomMessage dialogo;
            prompt selSet;

            if (mode == -1)
            {
                selSet = new prompt("Select Pressure Sensor", "Pressure sensor #:", 1, 2);
                selSet.ShowDialog();

                if (selSet.value == "")
                {
                    MessageBox.Show("Connection to CanSat canceled");
                }
                else
                {

                    sensorSet = Convert.ToInt32(selSet.value) -1;

                    ports = SerialPort.GetPortNames();
                    dialogo = new CustomMessage("Communication Port", ports);

                    dialogo.customShow();
                    pos = dialogo.getPuerto();
                    if (pos > -1)
                    {
                        initTrans();

                        portName = ports[pos];
                        serialPort.PortName = portName;
                        serialPort.BaudRate = 9600;
                        serialPort.Open();
                        mode = 5;
                        MessageBox.Show("Connected to port " + portName);

                        

                       // buttonStop.Visible = true;
                        //buttonStart.Visible = true;
                        //buttonConnect.Visible = false;
                        labelConnected.Visible = true;
                        //buttonSaveAll.Visible = false;
                        //buttonSaveCsv.Visible = false;

                    /*buttonStop.Visible = true;
                        buttonStart.Visible = true;
                        buttonConnect.Visible = false;
                        labelConnected.Visible = true;
                        buttonSaveAll.Visible = false;
                        buttonSaveCsv.Visible = false;

                        listReceivedPacketsContainer.Visible = true;
                        listReceivedPacketsPayload.Visible = true;
                        listCsvPacketsC.Visible = false;
                        listCsvPacketsP.Visible = false;

                        mode = 5;/*/

                    }
                    else
                    {
                        portName = "";
                        MessageBox.Show("Not connected");
                    }
                }
            }
        }

        private void radioButtonSelfTest_CheckedChanged(object sender, EventArgs e)
        {

        }

        private void labelPackets_Click(object sender, EventArgs e)
        {

        }

        private void radioButtonPackets_CheckedChanged(object sender, EventArgs e)
        {

        }

        private void labelTime_Click(object sender, EventArgs e)
        {

        }

        private void radioButtonTime_CheckedChanged(object sender, EventArgs e)
        {

        }

        private void buttonPassVolt_Click(object sender, EventArgs e)
        {
            trackBarVoltTest.Value = 0;
            resultsP[2] = "Passed";
        }

        private void buttonPassTemp_Click(object sender, EventArgs e)
        {
            trackBarTemTest.Value = 0;
        }

        private void buttonFailedTemp_Click(object sender, EventArgs e)
        {
            trackBarTemTest.Value = 1;
        }

        private void buttonFailedVolt_Click(object sender, EventArgs e)
        {
            trackBarVoltTest.Value = 1;
            resultsP[2] = "Falied";
        }

        private void buttonPassedPressC_Click(object sender, EventArgs e)
        {
            trackBarPressC.Value = 0;
        }

        private void buttonFailedPressC_Click(object sender, EventArgs e)
        {
            trackBarPressC.Value = 1;
        }

        private void panel7_Paint_1(object sender, PaintEventArgs e)
        {
            
        }

        private void button3_Click(object sender, EventArgs e)
        {
            requestP(17);
        }

        private void button17_Click(object sender, EventArgs e)
        {

        }

        private void chartAngle_Click(object sender, EventArgs e)
        {
            Random rand = new Random();
            chartAngleX.ChartAreas[0].AxisY.LabelStyle.Enabled = false;
            float val1 = rand.Next(361);
            chartAngleX.Series[0].Points.Clear();
            chartAngleX.Series[0].Points.AddXY(0, 0);
            chartAngleX.Series[0].Points.AddXY(val1, 1);

            MessageBox.Show("" + val1);


        }

        private void tabPage1_Click(object sender, EventArgs e)
        {

        }
    }


}
